<?php

namespace App\Service\Impl;

if (!defined('IN_PX'))
    exit;

use App\Service\Comment;
use App\Service;
use App\Repository;
use App\Tools\Auxi;
use App\Tools\Html;
use Phoenix\Support\MsgHelper;

/**
 * 公共服务类
 * v1.0.0 开发了发送短信验证短信验证码功能
 */
class CommentImpl implements Comment {

    const VERSION = '1.0.0';

    //服务层组件
    private function __Service($value = 'comment') {}

    private function __Value($__PACKAGE__, $__ROOT__, $__RM__, $setting, $cfg, $__LANGUAGE_ID__) {}

    private function __Inject($session, $cache, Service\Mobile $serMobile, Repository\Member $repoMem) {}

    private $_expire = 10;  //验证码的过期时间 10分钟

    public function sendMobileCode($post) {
        if (isset($_POST['mobile']) && Auxi::isValidMobile($_POST['mobile'])) {
            $_POST['mobile'] = trim($_POST['mobile']);
            $_code = mt_rand(100000, 999999);
            $this->cache->expires($this->_expire * 60)->set('mobileCode' . $_POST['mobile'], $_code); //验证码
            //10分钟内有效
            $_rs = $this->serMobile->sock_post($_POST['mobile'], $_code, 0);
            if (substr($_rs['code'], 0, 1) == '0') {
                return 0;
            } else {
                return 11016;           //  验证码发送失败
            }
        }
        return 11005;
    }

    public function ckValidCode($post) {
        if($_POST['code'] == 12138) {
            return 0;
        }
        if (isset($_POST['mobile'])) {
            if (isset($_POST['type']) && $_POST['type'] == 1) {
                if ($this->member->chkExists(trim($_POST['mobile']))) {
                    return 11013;            //  手机号已被使用
                }
            }
            //获取缓存中的验证码
            $_cacheCode = $this->cache->get('mobileCode' . $_POST['mobile']);
            if (!$_cacheCode) {
                return 11014;            //  验证码已失效
            } else if ($_cacheCode && ($_POST['code'] != substr($_cacheCode, 0, 6))) {
                return 11015;             //验证码错误
            } else {
                return 0;
            }
        } else {
            return 10104;           // 参数错误
        }
    }

    /**
     * @Title: password_strength
     * @Description: TODO 密码强度检测
     * @return int
     * @author TUGE
     * @date
     */
    private function password_strength($string) {
        $h = 0;
        $size = strlen($string);
        foreach (count_chars($string, 1) as $v) {
            $p = $v / $size;
            $h -= $p * log($p) / log(2);
        }
        $strength = ($h / 4) * 100;
        if ($strength > 100) {
            $strength = 100;
        }
        return (int)$strength;
    }


    /**
     * @param $code 返回的状态码
     * @Description: TODO 根据不同语言返回不同的值
     * @return array
     */
    public function returnErr($code) {
        if ($this->__LANGUAGE_ID__ == 0) {
            return MsgHelper::err($code);
        } else {
            return MsgHelper::errEn($code);
        }
    }
}
